package com.yj.auto.helper;

import java.util.List;

import com.jfinal.kit.StrKit;
import com.yj.auto.Constants;
import com.yj.auto.core.base.online.SessionUser;
import com.yj.auto.core.web.system.model.Resource;
import com.yj.auto.core.web.system.model.Role;
import com.yj.auto.core.web.system.model.RoleResource;

public class AuthHelper {

	public static boolean auth(String uri, String resCode, Integer roleId) {
		if (StrKit.isBlank(uri)) {
			return true;
		}
		if (null == roleId) {
			return false;
		}
		Role role = AutoHelper.getRoleService().getCache(roleId);
		if (null == role) {
			return false;
		}
		Resource resource = AutoHelper.getResourceService().getCacheByURI(uri);
		if (null == resource) {
			return false;
		}
		Integer resId = resource.getId();
		List<RoleResource> rrList = role.getResources();
		for (RoleResource rr : rrList) {
			if (resId.equals(rr.getResId())) {// 资源ID相等
				if (StrKit.isBlank(resCode)) {
					return true;
				} else if (resCode.equals(rr.getResCode())) {// 资源编号相等
					return true;
				} else if (Constants.AUTH_CODE_ALL.equals(rr.getResCode())) {// 拥有此资源所有权限
					if (resource.existsRes(Constants.AUTH_CODE_ALL)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static boolean auth(String uri, String resCode, Integer[] roles) {
		if (StrKit.isBlank(uri)) {
			return true;
		}
		if (null == roles)
			return false;
		for (Integer roleId : roles) {
			if (auth(uri, resCode, roleId)) {
				return true;
			}
		}
		return false;
	}

	public static boolean auth(String uri, String resCode, SessionUser su) {
		if (null == su)
			return false;
		if (su.isSuperUser()) {// 超级用户，拥有所有权限
			return true;
		}
		if (StrKit.isBlank(uri)) {
			return true;
		}
		return auth(uri, resCode, su.getRoles());
	}
}
